using System;
using System.Collections.Generic;
using System.Text;
using IBatisNet.DataMapper.Exceptions;
using IBatisNet.DataMapper.TypeHandlers;

namespace Shpm.System.Db
{
    public class CharBooleanTypeHandlerCallback : ITypeHandlerCallback
    {
        private const string DB_TRUE_C_VAL = "Y";
        private const string DB_FALSE_C_VAL = "N";
        private const string DB_TRUE_I_VAL = "1";
        private const string DB_FALSE_I_VAL = "0";

        public object GetResult(IResultGetter getter)
        {
            if (getter.Value == null || getter.Value == DBNull.Value)
            {
                return null;
            }

            string dbVal = Convert.ToString(getter.Value);

            if (DB_TRUE_C_VAL.Equals(dbVal, StringComparison.OrdinalIgnoreCase) || DB_TRUE_I_VAL.Equals(dbVal))
            {
                return true;
            }
            else if (DB_FALSE_C_VAL.Equals(dbVal, StringComparison.OrdinalIgnoreCase) || DB_FALSE_I_VAL.Equals(dbVal))
            {
                return false;
            }
            else
                throw new DataMapperException();
        }

        public void SetParameter(IParameterSetter setter, object parameter)
        {
            if (parameter == null || parameter == DBNull.Value)
            {
                setter.Value = DBNull.Value;
            }
            else
            {
                setter.Value = Convert.ToBoolean(parameter) ? DB_TRUE_I_VAL : DB_FALSE_I_VAL;
            }
        }

        public object ValueOf(string nullValue)
        {
            if (DB_TRUE_C_VAL.Equals(nullValue, StringComparison.OrdinalIgnoreCase) || DB_TRUE_I_VAL.Equals(nullValue))
                return true;
            else if (DB_FALSE_C_VAL.Equals(nullValue, StringComparison.OrdinalIgnoreCase) || DB_FALSE_I_VAL.Equals(nullValue))
                return false;
            else
                throw new DataMapperException();
        }

        public object NullValue
        {
            get { return DBNull.Value; }
        }

    }
}
